<template>
  <a-modal
    v-model:visible="visible"
    :title="t('aiot.projectManage.chooseCustomer')"
    width="80%"
    height="600px"
    class="chooseContainer"
    @ok="handleOk"
  >
    <div class="h-120 choose-content">
      <GroupPage
        :search-form-props="{
          columns: grpColumns,
          showAddBtn: false,
        }"
        :group-title="t('aiot.customerManage.grpList')"
        :content-title="t('aiot.customerManage.customerList', { length: pagination?.total })"
        @search="onSearchCustomerGrp"
      >
        <template #group>
          <SpinSkeleton v-show="grpData.length > 0" :loading="grpLoading">
            <div class="flex flex-row flex-wrap items-center lg:block lg:flex-nowrap">
              <div
                v-for="(el, i) in grpData"
                :key="el.customerGroupId"
                class="py-2 px-4 mb-2 cursor-pointer mr-2 lg:mr-0"
                :class="[curIndex === i ? 'bg-opacity-10 bg-color-active' : 'bg-header']"
                @click="handleCheckModal(el, i)"
              >
                <div class="mb-1" :class="[curIndex === i ? 'text-color-active' : 'text-color-main']">
                  {{ el.customerGroupName }}
                </div>
                <div
                  :title="el.descriptions"
                  class="text-color-secondary text-sm overflow-hidden text-ellipsis whitespace-nowrap"
                  >{{ el.descriptions }}</div
                >
              </div>
            </div>
          </SpinSkeleton>
          <SlEmpty v-show="!grpLoading && grpData.length === 0" :description="emptyText"></SlEmpty>
        </template>
        <template #content>
          <SearchForm
            class="mb-0 mx-7 mt-6"
            :keyword-search-data="[{ label: t('aiot.customerManage.customerName'), key: 'searchText' }]"
            size="small"
            :show-add-btn="false"
            @search="onSearch"
          />
          <div class="flex-1 overflow-hidden">
            <SlTable
              class="mx-7 sl-pagination-px0"
              :columns="columns"
              row-key="customerId"
              :data-source="tableData"
              :pagination="pagination"
              :loading="tableLoading"
              :scroll="{ x: true, y: '300px' }"
              :row-selection="rowSelection"
              :search-model="searchModel"
              :ignore-keys="['customerGroupId']"
            >
              <template #bodyCell="{ column, record }">
                <div v-if="column.dataIndex === 'brandLogo'">
                  <img v-if="record.brandLogo" :src="record.brandLogo" alt="logo" class="h-16" />
                  <p v-else> - </p>
                </div>
              </template>
            </SlTable>
          </div>
        </template>
      </GroupPage>
    </div>
  </a-modal>
</template>
<script setup lang="ts">
import CURD from "/@/api/curd";
import SearchForm from "/@/components/SearchForm.vue";
import SlEmpty from "/@/components/SlEmpty.vue";
import GroupPage from "/@/components/GroupPage.vue";
import SpinSkeleton from "/@/components/common/SpinSkeleton.vue";
import SlTable from "/@/components/SlTable.vue";
import { ShowCURDModalOptions, CURDAction, CURDDialogExpose } from "/@/components/CURDDialog/models";
import { useI18n } from "/@/locales/useI18n";
import { onMounted, ref, shallowRef, watch } from "vue";
import { Api } from "/@/api/aiot/customerManage";
import { message } from "ant-design-vue";
import { CustomerGrpItem, CustomerItem, CustomerSearchModel } from "/@/api/aiot/customerManage/models";
import { useCURD } from "/@/hooks/useCURD";
import { useEmptyText } from "../hooks/useEmptyText";
import { RequestMethodEnum } from "../api/req/httpEnum";

const props = defineProps<{
  show: boolean;
}>();
const emits = defineEmits(["update:show", "ok"]);
const { t } = useI18n();
const visible = ref<boolean>(false);
const currentRow = ref();
const keywordSearchKeys = [{ label: "客户分组名称", key: "customerGroupName" }];
const curIndex = ref(-1);
const {
  curd: grpCurd,
  tableData: grpData,
  tableLoading: grpLoading,
  reloadTable: grpReloadTable,
  searchModel: grpSearchModel,
} = useCURD<CustomerGrpItem>({
  getDataUrl: Api.getCustomerGroups,
  getDataMethod: RequestMethodEnum.GET,
  createUrl: Api.addCustomerGroups,
  updateUrl: Api.updateCustomerGroups,
  deleteUrl: Api.deleteCustomerGroupsByIds,
  loadOnMounted: false,
});
async function onSearchCustomerGrp(model) {
  await grpReloadTable({ searchText: model?.brandGroupName });
  handleIndexChange(0);
}
const grpIns = ref<CURDDialogExpose>();
const { emptyText, modelForEmptyText } = useEmptyText();
watch(
  grpSearchModel,
  (v) => {
    modelForEmptyText.value = v;
  },
  { deep: true }
);
const { curd, tableData, tableLoading, reloadTable, pagination, searchModel } = useCURD<
  CustomerItem,
  CustomerSearchModel
>({
  getPageUrl: Api.getCustomerPage,
  createUrl: Api.addCustomers,
  updateUrl: Api.updateCustomers,
  deleteUrl: Api.deleteCustomersByIds,
  loadOnMounted: false,
});
const selectedRowKeys = ref<string[]>([]);
const curSelectedGrp = shallowRef<CustomerGrpItem>();
function handleIndexChange(index) {
  const grp = grpData.value[index];
  curSelectedGrp.value = grp;
  if (grp) {
    //根据所选分组 刷新品牌数据
    reloadTable({
      model: {
        customerGroupId: grp.customerGroupId,
      },
    });
  } else {
    tableData.value = [];
  }
}
function setGrpShowOptions(options: ShowCURDModalOptions) {
  grpShowOptions.value = options;
  if (options.action === "UPDATE") {
    // 更新当前所选数据
    curSelectedGrp.value = grpData.value[curIndex.value];
    grpShowOptions.value.record = curSelectedGrp.value;
  }
}
let curSelectedRow = ref<CustomerItem[]>([]);
function handleCheckModal(el, i) {
  curIndex.value = i;
  grpIns.value?.isOpen() && setGrpShowOptions({ action: CURDAction.UPDATE, record: el });
}
/**
 * {
                type: 'radio',
                selectedRowKeys,
                onChange(...keys) {
                  currentRow = keys;
                  selectedRowKeys = keys;
                },
              }
 */
const rowSelection = {
  type: "radio",
  onChange: (selectedRowKeys: string[], selectedRows: CustomerItem[]) => {
    curSelectedRow.value = selectedRows;
  },
  getCheckboxProps: (record: CustomerItem) => ({
    // disabled: record.name === "Disabled User", // Column configuration not to be checked
    // name: record.name,
  }),
};
async function onSearch(model) {
  await reloadTable({ model });
}
const grpShowOptions = shallowRef<ShowCURDModalOptions>();
const grpModel = ref<CustomerGrpItem>({
  customerGroupName: "",
  descriptions: "",
});
const grpColumns = [
  { title: t("aiot.customerManage.customerGroupName"), dataIndex: "customerGroupName", ellipsis: true, width: "80px" },
  { title: t("common.des"), dataIndex: "description", ellipsis: true, width: "80px" },
];
const columns = [
  {
    title: t("aiot.customerManage.customerName"),
    dataIndex: "customerName",
    width: 100,
  },
  {
    width: 120,
    title: t("aiot.customerManage.contactPerson"),
    dataIndex: "contactPerson",
  },
  {
    width: 120,
    title: t("aiot.customerManage.phone"),
    dataIndex: "phone",
  },
];
watch(
  () => props.show,
  async (v) => {
    visible.value = v;
    if (v) {
      await grpReloadTable({ searchText: "" });
      if (grpData.value.length > 0) {
        curIndex.value = 0;
        const record = grpData.value[0];
      }
    }
  }
);
watch(visible, (v) => {
  emits("update:show", v);
});
watch(curIndex, handleIndexChange);
function handleOk() {
  if (curSelectedRow.value?.length > 0) {
    emits("update:show", false);
    emits("ok", curSelectedRow.value);
  }
}
</script>
<style>
.chooseContainer .ant-modal-body {
  padding: 0;
}
.choose-content > div {
  padding: 0;
}
</style>
